<script setup lang="ts">
import {UploadFilled} from '@element-plus/icons-vue'
import {uploadDocument} from "../../apis/DocumentApi.js";
import {elPrompt} from "../../utils/elPrompt.ts";
import {ref} from "vue";
import router from "../../router/router.js";

const percentage = ref(0)

function upload(fileObject) {
  const file = fileObject.file
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    uploadDocument(file, onProgress, onFinish, onError)
  }
}

function onProgress(progressEvent) {
  const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
  percentage.value = progress
}

function onFinish(result) {
  if (result.status !== 200) return elPrompt(result.message, 'error')
  elPrompt("上传成功！", "success")
  router.push(`/document/edit/${result.data['id']}`)
}

function onError(error) {
  elPrompt(error, "error")
}
</script>

<template>
  <div class="upload">
    <el-upload
        drag
        multiple
        accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf"
        :http-request="upload"
    >
      <el-icon class="el-icon--upload">
        <upload-filled/>
      </el-icon>
      <div class="el-upload__text">
        拖动文件至此或<em>点击选择文件</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          支持doc/docx/xls/xlsx/ppt/pptx/doc/docx，文件大小不得超过100MB
        </div>
      </template>
    </el-upload>
  </div>
  <div class="progress">
    <el-progress :text-inside="true" :stroke-width="30" :percentage="percentage"/>
  </div>
</template>

<style scoped lang="less">
.upload {

}

.progress {
  width: 100%;
}
</style>